import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/model/GetFriendRequestListResultData.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/widget/ConfirmDialog.dart';
import 'package:easy_chat_app/commons/widget/UserHeadPortrait.dart';
import 'package:easy_chat_app/mobile/constants/MobileAppGlobalConstants.dart';
import 'package:easy_chat_app/mobile/page/MobileChatPage.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

class MobileFriendRequestDetailPageParams {
  GetFriendRequestListResultDataFriendRequestView friendRequestView;

  MobileFriendRequestDetailPageParams.create({required this.friendRequestView});
}

class MobileFriendRequestDetailPageChangeNotifier extends ChangeNotifier {}

class MobileFriendRequestDetailPage extends StatelessWidget {
  final Logger logger = Logger();

  MobileFriendRequestDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) {
          return MobileFriendRequestDetailPageChangeNotifier();
        })
      ],
      builder: (context, child) {
        MobileFriendRequestDetailPageParams pageParams =
            RouteUtils.currentRouteSettings().arguments
                as MobileFriendRequestDetailPageParams;
        AppUserDetail appUserDetail =
            context.read<AppUserDetailChangeNotifier>().getAppUserDetail();
        GetFriendRequestListResultDataFriendRequestView friendRequestView =
            pageParams.friendRequestView;
        GetFriendRequestListResultDataUserView otherUser =
            pageParams.friendRequestView.targetUser!;
        if (appUserDetail.id == friendRequestView.targetUserId) {
          otherUser = friendRequestView.fromUser!;
        }
        String remarkText = "${otherUser.nickname}:${friendRequestView.remark}";
        if (appUserDetail.id == friendRequestView.fromUserId) {
          remarkText = "我:${friendRequestView.remark}";
        }
        double showOperationBtn = (friendRequestView.status == 0) ? 1 : 0;
        if (friendRequestView.fromUserId == appUserDetail.id) {
          showOperationBtn = 0;
        }
        return Scaffold(
            appBar: AppBar(
              surfaceTintColor: MobileAppGlobalConstants.appBarSurfaceTintColor,
              backgroundColor: MobileAppGlobalConstants.appBarBackgroundColor,
              title: const Text("好友申请"),
              centerTitle: true,
            ),
            body: Container(
              color: const Color.fromRGBO(237, 237, 237, 1),
              child: Column(
                children: [
                  Container(
                    color: Colors.white,
                    height: 35,
                  ),
                  Container(
                    color: Colors.white,
                    child: Row(
                      children: [
                        const SizedBox(
                          width: 25,
                        ),
                        UserHeadPortrait.network(
                            size: 65,
                            userCode: otherUser.code!,
                            userHeadPortrait: otherUser.headPortrait!,
                            userHeadPortraitStoreType:
                                otherUser.headPortraitStoreType!),
                        const SizedBox(
                          width: 20,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text(
                              otherUser.nickname ?? "",
                              style: const TextStyle(
                                  fontSize: 20, color: Colors.black),
                            ),
                            Text(
                              "EC号: ${otherUser.code ?? ""}",
                              style: const TextStyle(
                                  fontSize: 14,
                                  color: Color.fromRGBO(115, 115, 115, 1)),
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    width: double.infinity,
                    padding: const EdgeInsets.only(
                        left: 25, right: 25, top: 15, bottom: 15),
                    child: Container(
                      padding: const EdgeInsets.all(15),
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(247, 247, 247, 1),
                          borderRadius: BorderRadius.circular(5),
                          border: const Border.fromBorderSide(BorderSide(
                              color: Color.fromRGBO(226, 226, 226, 1)))),
                      child: Text(
                        remarkText,
                        style: const TextStyle(
                            color: Color.fromRGBO(116, 116, 116, 1)),
                      ),
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    height: 30,
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  GestureDetector(
                    child: Opacity(
                      opacity: showOperationBtn,
                      child: Container(
                          width: double.infinity,
                          height: 55,
                          alignment: Alignment.center,
                          color: Colors.white,
                          child: const Text(
                            "通过请求",
                            style: TextStyle(
                                fontSize: 16,
                                color: Color.fromRGBO(87, 107, 149, 1)),
                          )),
                    ),
                    onTap: () async {
                      await _acceptFriendRequest(
                          context, friendRequestView, appUserDetail);
                    },
                  ),
                  Opacity(
                    opacity: showOperationBtn,
                    child: const SizedBox(
                      height: 1,
                    ),
                  ),
                  GestureDetector(
                    child: Opacity(
                      opacity: showOperationBtn,
                      child: Container(
                          width: double.infinity,
                          height: 55,
                          alignment: Alignment.center,
                          color: Colors.white,
                          child: const Text(
                            "拒绝请求",
                            style: TextStyle(fontSize: 16, color: Colors.red),
                          )),
                    ),
                    onTap: () async {
                      await _rejectFriendRequest(
                          context, friendRequestView, appUserDetail);
                    },
                  )
                ],
              ),
            ));
      },
    );
  }

  Future<void> _acceptFriendRequest(
      BuildContext context,
      GetFriendRequestListResultDataFriendRequestView friendRequestView,
      AppUserDetail appUserDetail) async {
    GetFriendRequestListResultDataUserView otherUser =
        friendRequestView.targetUser!;
    if (appUserDetail.id == friendRequestView.targetUserId) {
      otherUser = friendRequestView.fromUser!;
    }
    var result = await ConfirmDialog.show(context,
        content: Text("确定要通过 ${otherUser.nickname} 的好友申请么?"));
    if (result) {
      var result = await HttpUtils.acceptFriendRequest(friendRequestView.id!);
      if (result.code == 0) {
        LocalConversation localConversation =
            await LocalConversationService.syncConversation2Local(
                LocalConversationTypeConstants.general, otherUser.id, null);
        RouteUtils.pop();
        await RouteUtils.route2MobileChatPage(MobileChatPageParams(
            currentUserId: appUserDetail.id,
            currentUserCode: appUserDetail.code,
            currentUserNickName: appUserDetail.nickname,
            currentUserHeadPortrait: appUserDetail.headPortrait,
            currentUserHeadPortraitStoreType:
                appUserDetail.headPortraitStoreType,
            contactUserId: otherUser.id,
            contactUserCode: otherUser.code,
            contactUserNickname: otherUser.nickname,
            contactUserHeadPortrait: otherUser.headPortrait,
            contactUserHeadPortraitStoreType: otherUser.headPortraitStoreType,
            localConversation: localConversation));
      } else {
        RouteUtils.pop();
        await Fluttertoast.showToast(
            msg: result.message ?? "系统错误", toastLength: Toast.LENGTH_SHORT);
      }
    }
  }

  Future<void> _rejectFriendRequest(
      BuildContext context,
      GetFriendRequestListResultDataFriendRequestView friendRequestView,
      AppUserDetail appUserDetail) async {
    GetFriendRequestListResultDataUserView otherUser =
        friendRequestView.targetUser!;
    if (appUserDetail.id == friendRequestView.targetUserId) {
      otherUser = friendRequestView.fromUser!;
    }
    var result = await ConfirmDialog.show(context,
        content: Text("确定要拒绝 ${otherUser.nickname} 的好友申请么?"));
    if (result) {
      var result = await HttpUtils.rejectFriendRequest(friendRequestView.id!);
      logger.i("result:$result");
      RouteUtils.pop();
      if (result.code == 0) {
        await Fluttertoast.showToast(
            msg: "操作成功", toastLength: Toast.LENGTH_SHORT);
      } else {
        await Fluttertoast.showToast(
            msg: result.message ?? "系统错误", toastLength: Toast.LENGTH_SHORT);
      }
    }
  }
}
